package com.bestv.search.spider.dao.hibernate;

import com.bestv.search.spider.dao.PersonDao;
import com.bestv.search.spider.model.Person;
import com.bestv.search.spider.model.Product;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class PersonDaoHibernate extends GenericDaoHibernate<Person, Long> implements PersonDao {
    public PersonDaoHibernate() {
        super(Person.class);
    }

    @Override
    public Person getById(String personId, String source) {
        String hql = "from Person where personId = ? and source = ? ";
        List<?> list = getHibernateTemplate().find(hql, new String[]{personId, source});
        return list == null || list.size() == 0 ? null : (Person) list.get(0);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Person> getByUpdateTime(Date date) {
        // Gets date before 60 years
        Calendar c = Calendar.getInstance();
        c.add(Calendar.YEAR, -60);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String birthdayOfSixty = df.format(c.getTime());

        String hql = "from Person where updateTime < ? and (birthday > ? or birthday is null) ";
        return getHibernateTemplate().find(hql, new Object[]{date, birthdayOfSixty});
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Person> getByNullAvatar_Iqiyi() {
        String hql = "from Person where avatar_iqiyi is null ";
        return getHibernateTemplate().find(hql);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Product> getProductsByPersonId(String personeId) {
        String hql = "from Product where personId=?";
        return getHibernateTemplate().find(hql, new Object[]{personeId});
    }
}
